package com.example.tiptravel.commom.utils;

import android.content.Context;
import android.os.Environment;

import com.bumptech.glide.Glide;
import com.bumptech.glide.GlideBuilder;
import com.bumptech.glide.integration.okhttp3.OkHttpGlideModule;
import com.bumptech.glide.load.DecodeFormat;
import com.bumptech.glide.load.engine.cache.DiskLruCacheFactory;
import com.bumptech.glide.load.engine.cache.InternalCacheDiskCacheFactory;
import com.bumptech.glide.load.engine.cache.LruResourceCache;
import com.bumptech.glide.load.engine.cache.MemorySizeCalculator;

import java.io.File;

import static com.bumptech.glide.load.engine.cache.DiskCache.Factory.DEFAULT_DISK_CACHE_SIZE;

/**
 * Created by Mr.zhou on 2016/10/27.
 */

public class AppGlideModule extends OkHttpGlideModule {

    public static final String DISK_CACHE_DIR = "imageCache";

    @Override
    public void applyOptions(Context context, GlideBuilder builder) {
        super.applyOptions(context, builder);
        //设置图片的显示格式
        builder.setDecodeFormat(DecodeFormat.PREFER_RGB_565);
        //指定内部存储路径
        builder.setDiskCache(new InternalCacheDiskCacheFactory(context, DISK_CACHE_DIR, DEFAULT_DISK_CACHE_SIZE));
        //自定义保存路径
        builder.setDiskCache(new DiskLruCacheFactory(getImageCache(context), DEFAULT_DISK_CACHE_SIZE));
        //设置内存大小
        MemorySizeCalculator memorySizeCalculator = new MemorySizeCalculator(context);
        int memoryCacheSize = memorySizeCalculator.getMemoryCacheSize();
        int memorySize = (int) (1.2 * memoryCacheSize);
        builder.setMemoryCache(new LruResourceCache(memorySize));
    }


    public String getImageCache(Context context) {
        String path;
        if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
            path = Environment.getExternalStorageDirectory() + File.separator + "bilibili/image/cache";
        } else {
            path = Environment.getDataDirectory() + File.separator + context.getPackageName() + File.separator + "image/cache";
        }
        return path;
    }

    @Override
    public void registerComponents(Context context, Glide glide) {
        super.registerComponents(context, glide);
    }
}
